﻿#include "rpc_forwarder.h"

#include "log.h"
#include "pb/svr/forward_from_base.pb.h"  // for ForwardResponse
#include "rpc/rpc_call_context.h"  // for CRpcCallContext()
#include "rpc/rpc_helper.h"  // for RpcHelper
#include "rpc_router.h"  // for CRpcRouter

const char LOG_NAME[] = "CRpcForwarder";

CRpcForwarder::CRpcForwarder(uint16_t uServerId)
	: m_uServerId(uServerId)
{
}

// Todo: ParseFromString(sContent) -> RpcHelper::ParseMsgFromStr()

static void HandleForwardResponse(const CRpcCallContext& ctx,
	const std::string& sContent)
{
	svr::ForwardResponse fwdResp;
	if (RpcHelper::ParseMsgFromStr(sContent, fwdResp))
		RpcHelper::ReplyTo(ctx, fwdResp.content());
}

bool CRpcForwarder::Forward(const CRpcCallContext& ctx,
		const std::string& sService, const std::string& sMethod,
		const std::string& sContent) const
{
	LOG_DEBUG("Forward: " << sService << "." << sMethod);
	uint16_t uCellSvrId = CRpcRouter::get_const_instance().GetDstSvrId(
		ctx.GetRpcCltId(), sService, sMethod);
	if (0 == uCellSvrId) return false;

	svr::ForwardRequest fwdReq;
	fwdReq.set_service(sService);
	fwdReq.set_method(sMethod);
	fwdReq.set_content(sContent);
	svr::ForwardRequest::GameCltId* pGameCltId = fwdReq.mutable_game_clt_id();
	pGameCltId->set_base_svr_id(m_uServerId);
	pGameCltId->set_base_rpc_clt_id(ctx.GetRpcCltId());

	RpcHelper::RequestSvr(uCellSvrId, "svr.ForwardFromBase", "Forward",
		fwdReq, [ctx](const std::string& sContent) {
			HandleForwardResponse(ctx, sContent);
		});
	return true;
}
